package lib;

import java.io.*;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import java.util.logging.Level;
import java.util.logging.Logger;

/**
 * @file StreamSocket.java
 * 
 * @version 0.1
 * @author Chris Sewell 10008342
 */
public class StreamSocket {

	Socket socket;
	OutputStream streamOut;
	OutputStreamWriter streamWriter;
	PrintWriter socketOut;

	InputStream streamIn;
	InputStreamReader streamReader;
	BufferedReader socketIn;
	boolean status;

	public StreamSocket(Socket socket) throws IOException {
		this.socket = socket;

		streamOut = socket.getOutputStream();
		streamWriter = new OutputStreamWriter(streamOut);
		socketOut = new PrintWriter(streamWriter);

		streamIn = socket.getInputStream();
		streamReader = new InputStreamReader(streamIn);
		socketIn = new BufferedReader(streamReader);

		status = true;
	}

	/**
	 * These abstractions hide the try catch statements and flushes required for
	 * sending/receiving data
	 */
	public void sendString(String message) {// Send and flush a string
		socketOut.println(message);
		socketOut.flush();
	}

	public String recieveString() {// Receive a string
		try {
			return socketIn.readLine();
		} catch (IOException ex) {
		}
		return null;
	}

	public String displayDetail() {// Returns client socket info for server
									// console output
		InetAddress clientAddress;
		clientAddress = socket.getInetAddress();// Hostname will not show in
												// Windows 7 UWE
		return clientAddress.getHostName() + " "
				+ clientAddress.getHostAddress();
	}

	public void kill() throws IOException {// Close all socket objects
		status = false;
		socket.close();

		streamOut.close();
		streamWriter.close();
		socketOut.close();

		streamIn.close();
		streamReader.close();
		socketIn.close();
	}

	public boolean isOpen() {
		return status;
	}

	public void updateHost(String host) throws UnknownHostException, IOException
	{
		socket = new Socket(host, 3434);
	}
	public String getCurrentHost()
	{
		InetAddress host;
		host = socket.getInetAddress();
		return host.getHostName();
	}
}
